#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "typedef.h"
#include "common.h"
#include "env.h"
#include "log.h"
#include "taskctrl.h"
#include "netctrl.h"
#include "timerctrl.h"

extern int  on_received(char*, int);
extern void on_timer();
extern void on_handshake(PDATA_PACKAGE);
extern void on_run(PDATA_PACKAGE);
static int daemon_init();

/*
 * By Tuwei
 * the main process should be the daemon process which will never be saw in
 * shell and also cannot communicate with user. It is a back ground process.
 *
 * The way as I looked up so far is that you must create a child process fist.
 * and let the father process exist.ofcourse ,there is some tasks you have to
 * do such as changing the file's access priority form the father process to
 * the new one.
 */
int main(int argc,char *argv[])
{
	//1. get env setting.
	if (env_init() != SUCCESS)
	{
		// print the error information.
		printf ("Unable to load the envirment setting data.");
		// exit the app.
		return 1;
	}
#if 1
	//2. translate to deamon.
	if (deamon_init() != SUCCESS)
	{
		// text out the error information.
		printf ("Unable to translate to deamon status.");
		// exit the app.
		return 2;
	}
#endif

	//3. initialize the log sys.
	if (log_init() != SUCCESS)
	{  
		// text out the error information.
		printf ("Unable to create log file.");
		// exit the app;
		return 0;
	}

	taskctrl_init();

	while(TRUE)
	{
		if (netctrl_connect() == SUCCESS)
		{
			// Start the flush action when the network been built.
			tmrctrl_start(on_timer, g_flush_time);
			// Text out the notice.
		  	log_alert(LT_NOTICE, "CONNECT");
		  	// Start receive the data from the server.
			if (netctrl_listen(on_received) != SUCCESS)
			{
				// Stop the flush action when the network disconnected.
				tmrctrl_stop();
				// Text out the notice.
				log_alert(LT_NOTICE, "DISCONNECT");
			}
		}

		sleep(g_reconn_interval_time);
	}

	netctrl_close();

	taskctrl_release();

	log_release();

	return 0;
}

int deamon_init(void)
{
     pid_t pid;
     if (( pid = fork()) < 0 )
     {
         return ERROR;
     }
     else if ( pid != 0 )
     {
         exit(0);
     }

     setsid();
     chdir("/");
     umask(0);

     return SUCCESS;
}


